/*/////////////////////////////////////////////////////////////////////////////

  The MIT License

  Copyright (c) 2008 - 2010. Dimarik

  Permission is hereby granted, free of charge, to any person obtaining a copy
  of this software and associated documentation files (the "Software"), to deal
  in the Software without restriction, including without limitation the rights
  to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  copies of the Software, and to permit persons to whom the Software is
  furnished to do so, subject to the following conditions:

  The above copyright notice and this permission notice shall be included in
  all copies or substantial portions of the Software.

  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  THE SOFTWARE.

/////////////////////////////////////////////////////////////////////////////*/

package ru.goodcore.display {

import flash.display.Bitmap;
import flash.display.BitmapData;
import flash.display.DisplayObject;
import flash.display.IBitmapDrawable;
import flash.errors.IllegalOperationError;
import flash.geom.Matrix;
import flash.geom.Rectangle;

/**
 * @author					BlooDHounD
 * @version					1.0
 * @playerversion			Flash 9
 * @langversion				3.0
 *
 * @keyword					bitmapmovieclip, bitmap, movieclip
 */
public class BitmapMovieClip extends MovieClipEquivalent {

	//-------------------------------------------------------------------------
	//
	//  Class variables
	//
	//-------------------------------------------------------------------------

	private static const _EMPTY:BitmapData = new BitmapData(1, 1, true, 0x000000);

	//-------------------------------------------------------------------------
	//
	//  Class private methods
	//
	//-------------------------------------------------------------------------

	/**
	 * @private
	 * @param bitmap
	 * @return 
	 */
	private static function getElement(bitmap:IBitmapDrawable):CollectionElement {
		var bmp:	BitmapData;
		var x:		Number = 0;
		var y:		Number = 0;
		if ( bitmap is BitmapData ) {
			bmp = BitmapData(bitmap);
		} else if ( bitmap is Bitmap ) {
			bmp = Bitmap(bitmap).bitmapData;
		} else if ( bitmap is DisplayObject ) {
			var obj:DisplayObject = DisplayObject(bitmap);
			var bounds:Rectangle = obj.getBounds( obj );
			if ( bounds.width > 0 && bounds.height > 0 ) {
				bmp = new BitmapData( bounds.width, bounds.height, true, 0x00000000 );
				bmp.draw( obj, new Matrix(1, 0, 0, 1, 1 - bounds.left, 1 - bounds.top) );
				x = bounds.left - 1;
				y = bounds.top - 1;
			} else {
				bmp = _EMPTY;
			}
		}
		return new CollectionElement( bmp, x, y );
	}

	//-------------------------------------------------------------------------
	//
	//  Constructor
	//
	//-------------------------------------------------------------------------

	/**
	 * Constructor
	 */
	public function BitmapMovieClip(pixelSnapping:String="auto", smoothing:Boolean=false) {
		super();
		this._container.pixelSnapping = pixelSnapping;
		this._container.smoothing = smoothing;
		super.addChild(this._container);
	}

	//-------------------------------------------------------------------------
	//
	//  Protected constants
	//
	//-------------------------------------------------------------------------

	/**
	 * @private
	 */
	protected const list:		Array = new Array();

	//-------------------------------------------------------------------------
	//
	//  Private constants
	//
	//-------------------------------------------------------------------------

	/**
	 * @private
	 */
	private const _container:	Bitmap = new Bitmap();

	//-------------------------------------------------------------------------
	//
	//  Properties
	//
	//-------------------------------------------------------------------------
	
	//---------------------------------
	//  pixelSnapping
	//---------------------------------

	public function get pixelSnapping():String {
		return this._container.pixelSnapping;
	}

	/**
	 * @private
	 */
	public function set pixelSnapping(value:String):void {
		this._container.pixelSnapping = value;
	}

	//---------------------------------
	//  smoothing
	//---------------------------------

	public function get smoothing():Boolean {
		return this._container.smoothing;
	}

	/**
	 * @private
	 */
	public function set smoothing(value:Boolean):void {
		this._container.smoothing = value;
	}

	//---------------------------------
	//  bitmapData
	//---------------------------------

	public function get bitmapData():BitmapData {
		return this._container.bitmapData;
	}

	//---------------------------------
	//  relativeX
	//---------------------------------

	public function get relativeX():Number {
		return this._container.x;
	}

	//---------------------------------
	//  relativeY
	//---------------------------------

	public function get relativeY():Number {
		return this._container.y;
	}

	//-------------------------------------------------------------------------
	//
	//  Overriden methods: MovieClip
	//
	//-------------------------------------------------------------------------

	[Deprecated(message="The method is deprecated", replacement="ru.goodcore.display.BitmapMovieClip#addBitmap")]
	/**
	 * @private
	 */
	public override function addChild(child:DisplayObject):DisplayObject {
		throw new IllegalOperationError();
	}

	[Deprecated(message="The method is deprecated", replacement="ru.goodcore.display.BitmapMovieClip#addBitmapAt")]
	/**
	 * @private
	 */
	public override function addChildAt(child:DisplayObject, index:int):DisplayObject {
		throw new IllegalOperationError();
	}

	[Deprecated(message="The method is deprecated", replacement="ru.goodcore.display.BitmapMovieClip#removeBitmap")]
	/**
	 * @private
	 */
	public override function removeChild(child:DisplayObject):DisplayObject {
		throw new IllegalOperationError();
	}

	[Deprecated(message="The method is deprecated", replacement="ru.goodcore.display.BitmapMovieClip#removeBitmapAt")]
	/**
	 * @private
	 */
	public override function removeChildAt(index:int):DisplayObject {
		throw new IllegalOperationError();
	}

	[Deprecated(message="The method is deprecated", replacement="ru.goodcore.display.BitmapMovieClip#getBitmapAt")]
	/**
	 * @private
	 */
	public override function getChildAt(index:int):DisplayObject {
		throw new IllegalOperationError();
	}

	[Deprecated(message="The method is deprecated", replacement="ru.goodcore.display.BitmapMovieClip#getBitmapIndex")]
	/**
	 * @private
	 */
	public override function getChildIndex(child:DisplayObject):int {
		throw new IllegalOperationError();
	}

	[Deprecated(message="The method is deprecated")]
	/**
	 * @private
	 */
	public override function getChildByName(name:String):DisplayObject {
		throw new IllegalOperationError();
	}

	[Deprecated(message="The method is deprecated", replacement="ru.goodcore.display.BitmapMovieClip#setBitmapIndex")]
	/**
	 * @private
	 */
	public override function setChildIndex(child:DisplayObject, index:int):void {
		throw new IllegalOperationError();
	}

	[Deprecated(message="The method is deprecated", replacement="ru.goodcore.display.BitmapMovieClip#swapBitmaps")]
	/**
	 * @private
	 */
	public override function swapChildren(child1:DisplayObject, child2:DisplayObject):void {
		throw new IllegalOperationError();
	}

	[Deprecated(message="The method is deprecated", replacement="ru.goodcore.display.BitmapMovieClip#swapBitmapsAt")]
	/**
	 * @private
	 */
	public override function swapChildrenAt(index1:int, index2:int):void {
		throw new IllegalOperationError();
	}

	[Deprecated(message="The method is deprecated", replacement="ru.goodcore.display.BitmapMovieClip#containsBitmap")]
	/**
	 * @private
	 */
	public override function contains(child:DisplayObject):Boolean {
		throw new IllegalOperationError();
	}

	//-------------------------------------------------------------------------
	//
	//  Methods
	//
	//-------------------------------------------------------------------------

	/**
	 * @param	bind	если установлен в true, то копирует только ссылки на эленты, оставляя связывание.
	 */
	public function clone(bind:Boolean=true):BitmapMovieClip {
		var result:BitmapMovieClip = new BitmapMovieClip( this._container.pixelSnapping, this._container.smoothing );
		if ( bind ) {
			result.list.push.apply( result.list, this.list );
		} else {
			var len:uint = this.list.length;
			for ( var i:uint = 0; i < len; i++ ) {
				result.list.push( CollectionElement(this.list[i]).clone() );
			}
		}
		result._totalFrames = this._totalFrames;
		return result;
	}

	public function addBitmap(bitmap:IBitmapDrawable, x:Number=0, y:Number=0):BitmapData {
		var element:CollectionElement = getElement( bitmap );
		element.x += x;
		element.y += y;
		this.list.push( element );
		this._totalFrames++;
		return element.bmp;
	}

	public function addBitmapAt(bitmap:IBitmapDrawable, index:int, x:Number=0, y:Number=0):BitmapData {
		var element:CollectionElement = getElement( bitmap );
		element.x += x;
		element.y += y;
		this.list.splice( index, 0, element );
		this._totalFrames++;
		if ( index <= this._currentFrame ) this._currentFrame++;
		return element.bmp;
	}

	public function removeBitmap(bitmap:BitmapData):BitmapData {
		return this.$removeBitmapAt( this.$getBitmapIndex( bitmap ) );
	}

	public function removeBitmapAt(index:int):BitmapData {
		return this.$removeBitmapAt( index );
	}

	public function getBitmapAt(index:int):BitmapData {
		return this.$getBitmapAt( index );
	}

	public function getBitmapIndex(bitmap:BitmapData):int {
		return this.$getBitmapIndex( bitmap );
	}

	public function setBitmapIndex(bitmap:BitmapData, index:int):void {
		this.$setBitmapIndex( bitmap, index );
	}

	public function swapBitmaps(bitmap1:BitmapData, bitmap2:BitmapData):void {
		this.$swapBitmaps( bitmap1, bitmap2, this.$getBitmapIndex( bitmap1 ), this.$getBitmapIndex( bitmap2 ) );
	}

	public function swapBitmapsAt(index1:int, index2:int):void {
		this.$swapBitmaps( this.getBitmapAt( index1 ), this.getBitmapAt( index2 ), index1, index2 );
	}

	public function containsBitmap(bitmap:BitmapData):Boolean {
		return this.$getBitmapIndex( bitmap ) >= 0;
	}

	public function dispose():void {
		this._container.bitmapData = null;
		while ( this.list.length ) {
			CollectionElement(this.list.pop()).bmp.dispose();
		}
	}

	//-------------------------------------------------------------------------
	//
	//  Protected methods
	//
	//-------------------------------------------------------------------------

	protected override function setCurrentFrame(value:int):void {
		this._currentFrame = value;
		var element:CollectionElement = CollectionElement(this.list[value - 1]);
		this._container.bitmapData = element.bmp;
		this._container.x = element.x;
		this._container.y = element.y;
	}

	//-------------------------------------------------------------------------
	//
	//  Private methods
	//
	//-------------------------------------------------------------------------

	/**
	 * @private 
	 */
	private function $removeBitmapAt(index:Number):BitmapData {
		this._totalFrames--;
		return CollectionElement(this.list.splice(index, 1)[0]).bmp;
	}

	/**
	 * @private 
	 */
	private function $getBitmapIndex(bitmap:BitmapData):int {
		var len:uint = this.list.length;
		for ( var i:uint = 0; i < len; i++ ) {
			if ( CollectionElement(this.list[i]).bmp === bitmap ) 
				return i;
		}
		return -1;
	}

	/**
	 * @private 
	 */
	private function $getBitmapAt(index:int):BitmapData {
		return CollectionElement(this.list[index]).bmp;
	}

	/**
	 * @private 
	 */
	private function $setBitmapIndex(bitmap:BitmapData, index:int):void {
		this.list.splice( this.$getBitmapIndex( bitmap ), 1 );
		this.list.splice( index, 0, bitmap );
	}

	/**
	 * @private 
	 */
	private function $swapBitmaps(bmp1:BitmapData, bmp2:BitmapData, 
									index1:int, index2:int):void
	{
		if ( index1 > index2 ) {
			this.$setBitmapIndex( bmp1, index2 );
			this.$setBitmapIndex( bmp2, index1 );
		} else {
			this.$setBitmapIndex( bmp2, index1 );
			this.$setBitmapIndex( bmp1, index2 );
		}
	}

}
}

//=============================================================================
//
//  Inner definitions
//
//=============================================================================

import flash.display.BitmapData;
import ru.goodcore.utils.crypto.MD5;

///////////////////////////////////////////////////////////////////////////////
//
//  Helper class: CollectionElement
//
///////////////////////////////////////////////////////////////////////////////

internal final class CollectionElement {

	private static var _hash:Array = new Array();

	public function CollectionElement(bmp:BitmapData, x:Number=0, y:Number=0) {
		super();

		//var hash:String = MD5.hashBytes(bmp.getPixels(bmp.rect));

		//if ( !(hash in _hash) ) {
		//	_hash[hash] = bmp;
		//} else {
		//	bmp = BitmapData(_hash[hash]);
		//}

		this.bmp = bmp;
		this.x = x;
		this.y = y;
	}

	public var bmp:BitmapData;

	public var x:Number;

	public var y:Number;

	public function clone():CollectionElement {
		return new CollectionElement( this.bmp.clone(), this.x, this.y );
	}

}